/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.synchronization.remote.ws.converter;

import java.math.BigDecimal;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import javax.xml.datatype.XMLGregorianCalendar;
import systole.domain.analysis.results.averages.Average;
import systole.domain.analysis.results.averages.AverageByDecade;
import systole.domain.analysis.results.averages.AverageByDecadeFemale;
import systole.domain.analysis.results.averages.AverageByDecadeMale;
import systole.domain.clinicalInformation.ClinicalInformation;
import systole.domain.clinicalInformation.Family;
import systole.domain.clinicalInformation.FamilyPatientBackground;
import systole.domain.clinicalInformation.FamilyPatientBackgroundId;
import systole.domain.clinicalInformation.HabitPatient;
import systole.domain.clinicalInformation.Medicine;
import systole.domain.clinicalInformation.MedicinePatient;
import systole.domain.clinicalInformation.MedicinePatientId;
import systole.domain.clinicalInformation.Pathology;
import systole.domain.clinicalInformation.PathologyPatient;
import systole.domain.clinicalInformation.PathologyPatientId;
import systole.domain.clinicalInformation.Sport;
import systole.domain.clinicalInformation.SportPatient;
import systole.domain.clinicalInformation.SportPatientId;
import systole.domain.clinicalInformation.Surgery;
import systole.domain.clinicalInformation.SurgeryPatient;
import systole.domain.clinicalInformation.SurgeryPatientId;
import systole.domain.persons.Medic;
import systole.domain.persons.Patient;
import systole.domain.persons.identityCard.IdentityCard;
import systole.domain.persons.identityCard.IdentityCardType;
import systole.domain.persons.profession.Profession;
import systole.domain.signals.SignalFrequency;
import systole.exceptions.ExceptionDAO;
import systole.persistence.FacadeDB;
import systole.synchronization.remote.entities.ClinicalInfoRemote;
import systole.synchronization.remote.entities.FamilyRemote;
import systole.synchronization.remote.entities.IdentityCardTypeRemote;
import systole.synchronization.remote.entities.MedicRemote;
import systole.synchronization.remote.entities.MedicineRemote;
import systole.synchronization.remote.entities.PathologyRemote;
import systole.synchronization.remote.entities.PatientRemote;
import systole.synchronization.remote.entities.ProfessionRemote;
import systole.synchronization.remote.entities.SignalFrequencyRemote;
import systole.synchronization.remote.entities.SportRemote;
import systole.synchronization.remote.entities.SurgeryRemote;
import systole.synchronization.remote.ws.AverageWs;
import systole.synchronization.remote.ws.AveragesWs;
import systole.synchronization.remote.ws.ClinicalInfoWs;
import systole.synchronization.remote.ws.FamilyWs;
import systole.synchronization.remote.ws.IdentityCardTypeWs;
import systole.synchronization.remote.ws.IdentityCardWs;
import systole.synchronization.remote.ws.MedicWs;
import systole.synchronization.remote.ws.MedicineWs;
import systole.synchronization.remote.ws.PathologyWs;
import systole.synchronization.remote.ws.PatientFamilyWs;
import systole.synchronization.remote.ws.PatientHabitsWs;
import systole.synchronization.remote.ws.PatientMedicineWs;
import systole.synchronization.remote.ws.PatientPathologyWs;
import systole.synchronization.remote.ws.PatientSportWs;
import systole.synchronization.remote.ws.PatientSurgeryWs;
import systole.synchronization.remote.ws.PatientWs;
import systole.synchronization.remote.ws.ProfessionWs;
import systole.synchronization.remote.ws.SignalFrequencyWs;
import systole.synchronization.remote.ws.SportWs;
import systole.synchronization.remote.ws.SurgeryWs;

/**
 *
 * @author jmj
 */
public class ConverterToLocalEntity {

    public ConverterToLocalEntity() {
        super();
    }

    /**
     *
     * @param patientWs
     * @throws ExceptionDAO
     */
    public void savePatient(PatientWs patientWs) throws ExceptionDAO {
        if (patientWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Patient patient = new Patient();
        patient.setName(patientWs.getName());
        patient.setSurname(patientWs.getSurname());
        patient.setBirthdate(this.xmlGregorianCalendarToDate(patientWs.getBirthdate()));
        patient.setAddress(patientWs.getAddress());
        patient.setCity(patientWs.getCity());
        patient.setSex(patientWs.isSex() ? "M" : "F");
        patient.setTelephone(patientWs.getTelephone());
        patient.setEmail(patientWs.getEmail());
        patient.setIdentityCard(this.convertToLocalIdentityCard(patientWs.getIdentityCard()));
        FacadeDB.getInstance().getPatientBroker().insert(patient);

        PatientRemote patientRemote = new PatientRemote();
        patientRemote.setRemoteId(patientWs.getId());
        patientRemote.setPatient(patient);
        FacadeDB.getInstance().getPatientSyncBroker().savePatientRemote(patientRemote);
        patient.setHabitPatient(this.convertToLocalHabitPatient(patientWs.getHabits(), patient));

        if (patientWs.getMedicines() != null) {
            Iterator<PatientMedicineWs> medicines = patientWs.getMedicines().iterator();
            while (medicines.hasNext()) {
                MedicinePatient medicinePatient = this.convertToLocalPatientMedicine(medicines.next(), patient);
                if (medicinePatient != null) {
                    patient.getMedicinesPatient().add(medicinePatient);
                }
            }
        }

        if (patientWs.getPathologies() != null) {
            Iterator<PatientPathologyWs> pathologies = patientWs.getPathologies().iterator();
            while (pathologies.hasNext()) {
                PathologyPatient pathologyPatient = this.convertToLocalPatientPathology(pathologies.next(), patient);
                if (pathologyPatient != null) {
                    patient.getPathologiesPatient().add(pathologyPatient);
                }
            }
        }

        if (patientWs.getSports() != null) {
            Iterator<PatientSportWs> sports = patientWs.getSports().iterator();
            while (sports.hasNext()) {
                SportPatient sportPatient = this.convertToLocalPatientSport(sports.next(), patient);
                if (sportPatient != null) {
                    patient.getSportsPatient().add(sportPatient);
                }
            }
        }

        if (patientWs.getSurgeries() != null) {
            Iterator<PatientSurgeryWs> surgeries = patientWs.getSurgeries().iterator();
            while (surgeries.hasNext()) {
                SurgeryPatient surgeryPatient = this.convertToLocalPatientSurgery(surgeries.next(), patient);
                if (surgeryPatient != null) {
                    patient.getSurgeriesPatient().add(surgeryPatient);
                }
            }
        }

        if (patientWs.getFamilyBackground() != null) {
            Iterator<PatientFamilyWs> backgrounds = patientWs.getFamilyBackground().iterator();
            while (backgrounds.hasNext()) {
                FamilyPatientBackground background = this.convertToLocalPatientFamilyBackground(backgrounds.next(), patient);
                if (background != null) {
                    patient.getFamilyPatientBackgrounds().add(background);
                }
            }
        }

        FacadeDB.getInstance().getPatientBroker().update(patient);
        FacadeDB.getInstance().commitTransaction();

    }

    /**
     * 
     * @param medicWs
     * @throws ExceptionDAO
     */
    public void saveMedic(MedicWs medicWs) throws ExceptionDAO {
        if (medicWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Medic medic = new Medic();
        medic.setName(medicWs.getName());
        medic.setSurname(medicWs.getSurname());
        medic.setAddress(medicWs.getAddress());
        medic.setBirthdate(this.xmlGregorianCalendarToDate(medicWs.getBirthdate()));
        medic.setCellphone(medicWs.getCellphone());
        medic.setCity(medicWs.getCity());
        medic.setEmail(medicWs.getEmail());
        medic.setTelephone(medicWs.getTelephone());
        medic.setIdentityCard(this.convertToLocalIdentityCard(medicWs.getIdentityCard()));
        FacadeDB.getInstance().getMedicBroker().insert(medic);
        MedicRemote medicRemote = new MedicRemote(medic);
        medicRemote.setRemoteId(medicWs.getId());
        FacadeDB.getInstance().getMedicSyncBroker().saveMedicRemote(medicRemote);
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param medicineWS
     * @throws ExceptionDAO
     */
    public void saveMedicine(MedicineWs medicineWS) throws ExceptionDAO {
        if (medicineWS == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Medicine medicine = FacadeDB.getInstance().getMedicineBroker().getMedicineByName(medicineWS.getName());
        if (medicine == null) {
            medicine = new Medicine();
            medicine.setName(medicineWS.getName());
            medicine.setDescription(medicine.getDescription());
            FacadeDB.getInstance().getMedicineBroker().insert(medicine);
            MedicineRemote medicineRemote = new MedicineRemote(medicine);
            medicineRemote.setRemoteId(medicineWS.getId());
            FacadeDB.getInstance().getMedicineSyncBroker().saveMedicineRemote(medicineRemote);
        } else {
            if (FacadeDB.getInstance().getMedicineSyncBroker().getMedicineRemoteByMedicine(medicine) == null) {
                MedicineRemote medicineRemote = new MedicineRemote(medicine);
                medicineRemote.setRemoteId(medicineWS.getId());
                FacadeDB.getInstance().getMedicineSyncBroker().saveMedicineRemote(medicineRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param pathologyWs
     * @throws ExceptionDAO
     */
    public void savePathology(PathologyWs pathologyWs) throws ExceptionDAO {
        if (pathologyWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Pathology pathology = FacadeDB.getInstance().getPathologyBroker().getPathologyByName(pathologyWs.getName());
        if ((pathology == null) && (pathologyWs.getInitials() != null)) {
            pathology = FacadeDB.getInstance().getPathologyBroker().getPathologyByInitials(pathologyWs.getInitials());
        }
        if (pathology == null) {
            pathology = new Pathology();
            pathology.setName(pathologyWs.getName());
            pathology.setDescription(pathologyWs.getDescription());
            pathology.setInitials(pathologyWs.getInitials());
            FacadeDB.getInstance().getPathologyBroker().insert(pathology);
            PathologyRemote pathologyRemote = new PathologyRemote(pathology);
            pathologyRemote.setRemoteId(pathologyWs.getId());
            FacadeDB.getInstance().getPathologySyncBroker().savePathologyRemote(pathologyRemote);
        } else {
            if (FacadeDB.getInstance().getPathologySyncBroker().getPathologyRemoteByPathology(pathology) == null) {
                PathologyRemote pathologyRemote = new PathologyRemote(pathology);
                pathologyRemote.setRemoteId(pathologyWs.getId());
                FacadeDB.getInstance().getPathologySyncBroker().savePathologyRemote(pathologyRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param sportWs
     * @throws ExceptionDAO
     */
    public void saveSport(SportWs sportWs) throws ExceptionDAO {
        if (sportWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();

        Sport sport = FacadeDB.getInstance().getSportBroker().getSportByName(sportWs.getName());
        if (sport == null) {
            sport = new Sport();
            sport.setName(sportWs.getName());
            sport.setDescription(sportWs.getDescription());
            FacadeDB.getInstance().getSportBroker().insert(sport);
            SportRemote sportRemote = new SportRemote(sport);
            sportRemote.setRemoteId(sportWs.getId());
            FacadeDB.getInstance().getSportSyncBroker().saveSportRemote(sportRemote);
        } else {
            if (FacadeDB.getInstance().getSportSyncBroker().getSportRemoteFromSport(sport) == null) {
                SportRemote sportRemote = new SportRemote(sport);
                sportRemote.setRemoteId(sportWs.getId());
                FacadeDB.getInstance().getSportSyncBroker().saveSportRemote(sportRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param familyWs
     * @throws ExceptionDAO
     */
    public void saveFamily(FamilyWs familyWs) throws ExceptionDAO {
        if (familyWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Family family = FacadeDB.getInstance().getFamilyBroker().getFamilyByName(familyWs.getName());
        if (family == null) {
            family = new Family();
            family.setName(familyWs.getName());
            family.setSex(familyWs.isSex() ? "M" : "F");
            FacadeDB.getInstance().getFamilyBroker().insert(family);
            FamilyRemote familyRemote = new FamilyRemote(family);
            familyRemote.setRemoteId(familyWs.getId());
            FacadeDB.getInstance().getFamilySyncBroker().saveFamilyRemote(familyRemote);
        } else {
            if (FacadeDB.getInstance().getFamilySyncBroker().getFamilyRemoteByFamily(family) == null) {
                FamilyRemote familyRemote = new FamilyRemote(family);
                familyRemote.setRemoteId(familyWs.getId());
                FacadeDB.getInstance().getFamilySyncBroker().saveFamilyRemote(familyRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param surgeryWs
     * @throws ExceptionDAO 
     */
    public void saveSurgery(SurgeryWs surgeryWs) throws ExceptionDAO {
        if (surgeryWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Surgery surgery = FacadeDB.getInstance().getSurgeryBroker().getSurgeryByName(surgeryWs.getName());
        if (surgery == null) {
            surgery = new Surgery();
            surgery.setName(surgeryWs.getName());
            surgery.setDescription(surgeryWs.getDescription());
            FacadeDB.getInstance().getSurgeryBroker().insert(surgery);
            SurgeryRemote surgeryRemote = new SurgeryRemote(surgery);
            surgeryRemote.setRemoteId(surgeryWs.getId());
            FacadeDB.getInstance().getSurgerySyncBroker().saveSurgeryRemote(surgeryRemote);
        } else {
            if (FacadeDB.getInstance().getSurgerySyncBroker().getSurgeryRemoteBySurgery(surgery) == null) {
                SurgeryRemote surgeryRemote = new SurgeryRemote(surgery);
                surgeryRemote.setRemoteId(surgeryWs.getId());
                FacadeDB.getInstance().getSurgerySyncBroker().saveSurgeryRemote(surgeryRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param signalFrequencyWs
     * @throws ExceptionDAO 
     */
    public void saveSignalFrequency(SignalFrequencyWs signalFrequencyWs) throws ExceptionDAO {
        if (signalFrequencyWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        SignalFrequency frequency = FacadeDB.getInstance().getSignalFrequencyBroker().getSignalFrequencyByName(signalFrequencyWs.getName());
        if (frequency == null) {
            frequency = new SignalFrequency();
            frequency.setFrequency(new BigDecimal(signalFrequencyWs.getFrequency()));
            frequency.setDescription(signalFrequencyWs.getName());
            FacadeDB.getInstance().getSignalFrequencyBroker().insert(frequency);
            SignalFrequencyRemote frequencyRemote = new SignalFrequencyRemote(frequency);
            frequencyRemote.setRemoteId(signalFrequencyWs.getId());
            FacadeDB.getInstance().getSignalFrequencySyncBroker().saveSignalFrequencyRemote(frequencyRemote);
        } else {
            if (FacadeDB.getInstance().getSignalFrequencySyncBroker().getFrequencyRemoteBySignalFrequency(frequency) == null) {
                SignalFrequencyRemote frequencyRemote = new SignalFrequencyRemote(frequency);
                frequencyRemote.setRemoteId(signalFrequencyWs.getId());
                FacadeDB.getInstance().getSignalFrequencySyncBroker().saveSignalFrequencyRemote(frequencyRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     *
     * @param clinicalInfoWs
     * @throws ExceptionDAO
     */
    public void saveClinicalInfo(ClinicalInfoWs clinicalInfoWs) throws ExceptionDAO {
        if (clinicalInfoWs == null) {
            return;
        }

        Patient patient = FacadeDB.getInstance().getPatientSyncBroker().getPatientByRemoteId(clinicalInfoWs.getPatientId());
        if (patient == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        ClinicalInformation clinicalInformation = new ClinicalInformation(patient);
        clinicalInformation.setYears(clinicalInfoWs.getAge());
        clinicalInformation.setInformationDate(this.xmlGregorianCalendarToDate(clinicalInfoWs.getDate()));
        clinicalInformation.setHeight(clinicalInfoWs.getHeight());
        clinicalInformation.setWeight(clinicalInfoWs.getWeight());
        clinicalInformation.setHdl(clinicalInfoWs.getHdl());
        clinicalInformation.setLdl(clinicalInfoWs.getLdl());
        clinicalInformation.setGlucemic(clinicalInfoWs.getGlucemic());
        clinicalInformation.setTriglycerides(clinicalInfoWs.getTriglycerides());
        clinicalInformation.setTotalCholesterol(clinicalInfoWs.getTotalCholesterol());
        clinicalInformation.setSystolicPressure(clinicalInfoWs.getSystolicPressure());
        clinicalInformation.setDiastolicPressure(clinicalInfoWs.getDiastolicPressure());
        FacadeDB.getInstance().getClinicalInfoBroker().insert(clinicalInformation);
        ClinicalInfoRemote clinicalInfoRemote = new ClinicalInfoRemote(clinicalInformation);
        clinicalInfoRemote.setRemoteId(clinicalInfoWs.getId());
        FacadeDB.getInstance().getClinicalInfoSyncBroker().saveClinicalInfoRemote(clinicalInfoRemote);
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param professionWs
     * @throws ExceptionDAO
     */
    public void saveProfession(ProfessionWs professionWs) throws ExceptionDAO {
        if (professionWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        Profession profession = FacadeDB.getInstance().getProfessionBroker().getProfessionByName(professionWs.getName());
        if (profession == null) {
            profession = new Profession();
            profession.setName(professionWs.getName());
            profession.setDescription(professionWs.getDescription());
            FacadeDB.getInstance().getProfessionBroker().insert(profession);
            ProfessionRemote professionRemote = new ProfessionRemote(profession);
            professionRemote.setRemoteId(professionWs.getId());
            FacadeDB.getInstance().getProfessionSyncBroker().saveProfessionRemote(professionRemote);
        } else {
            if (FacadeDB.getInstance().getProfessionSyncBroker().getProfessionRemoteByProfession(profession) == null) {
                ProfessionRemote professionRemote = new ProfessionRemote(profession);
                professionRemote.setRemoteId(professionWs.getId());
                FacadeDB.getInstance().getProfessionSyncBroker().saveProfessionRemote(professionRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     *
     * @param cardTypeWs
     * @throws ExceptionDAO
     */
    public void saveIdentityCardType(IdentityCardTypeWs cardTypeWs) throws ExceptionDAO {
        if (cardTypeWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        IdentityCardType cardType = FacadeDB.getInstance().getIdentityCardBroker().getIdentityCardTypeByName(cardTypeWs.getName());
        if (cardType == null) {
            cardType = new IdentityCardType();
            cardType.setDescription(cardTypeWs.getName());
            FacadeDB.getInstance().getIdentityCardBroker().save(cardType);
            IdentityCardTypeRemote cardTypeRemote = new IdentityCardTypeRemote(cardType);
            cardTypeRemote.setRemoteId(cardTypeWs.getId());
            FacadeDB.getInstance().getIdentityCardTypeSyncBroker().saveIdentityCardTypeRemote(cardTypeRemote);
        } else {
            if (FacadeDB.getInstance().getIdentityCardTypeSyncBroker().getIdentityCardTypeRemoteFromCardType(cardType) == null) {
                IdentityCardTypeRemote cardTypeRemote = new IdentityCardTypeRemote(cardType);
                cardTypeRemote.setRemoteId(cardTypeWs.getId());
                FacadeDB.getInstance().getIdentityCardTypeSyncBroker().saveIdentityCardTypeRemote(cardTypeRemote);
            }
        }
        FacadeDB.getInstance().commitTransaction();
    }

    /**
     * 
     * @param averagesWs
     * @throws ExceptionDAO
     */
    public void saveAverages(AveragesWs averagesWs) throws ExceptionDAO {
        if (averagesWs == null) {
            return;
        }
        FacadeDB.getInstance().startTransaction();
        FacadeDB.getInstance().getAveragesBroker().deleteAllAverages();


        if (averagesWs.getAverages() != null) {
            Iterator<AverageWs> itaod = averagesWs.getAverages().iterator();
            while (itaod.hasNext()) {
                AverageWs averageWs = itaod.next();
                AverageByDecade averageByDecade = averageWs.isSex()
                        ? new AverageByDecadeMale(averageWs.getDecade())
                        : new AverageByDecadeFemale(averageWs.getDecade());
                averageByDecade.setSamples(averageWs.getSamples());
                Average averageIAR = new Average();
                averageIAR.setAvg(averageWs.getIarAvg());
                averageIAR.setTrustInterval(averageWs.getIarTrustInterval());
                averageByDecade.setAverageIAR(averageIAR);
                Average averageAOD = new Average();
                averageAOD.setAvg(averageWs.getAodAvg());
                averageAOD.setTrustInterval(averageWs.getAodTrustInterval());
                averageByDecade.setAverageAOD(averageAOD);
                Average averageAOS = new Average();
                averageAOS.setAvg(averageWs.getAosAvg());
                averageAOS.setTrustInterval(averageWs.getAosTrustInterval());
                averageByDecade.setAverageAOS(averageAOS);
                FacadeDB.getInstance().getAveragesBroker().save(averageByDecade);
            }
        }

        FacadeDB.getInstance().commitTransaction();
    }

    /**
     *
     * @param identityCardWs
     * @return
     * @throws ExceptionDAO
     */
    private IdentityCard convertToLocalIdentityCard(IdentityCardWs identityCardWs) throws ExceptionDAO {
        if (identityCardWs == null) {
            return null;
        }
        IdentityCardType cardType = FacadeDB.getInstance().getIdentityCardTypeSyncBroker().getIdentityCardTypeByRemoteId(identityCardWs.getTypeId());
        if (cardType == null) {
            return null;
        }
        IdentityCard identityCard = new IdentityCard();
        identityCard.setNumber(identityCardWs.getNumber());
        identityCard.setCardType(cardType);
        return identityCard;
    }

    /**
     *
     * @param patientSportWs
     * @param patient
     * @return
     */
    private SportPatient convertToLocalPatientSport(PatientSportWs patientSportWs, Patient patient) throws ExceptionDAO {
        if (patientSportWs == null) {
            return null;
        }
        Sport sport = FacadeDB.getInstance().getSportSyncBroker().getSportByRemoteId(patientSportWs.getSportId());
        if (sport == null) {
            return null;
        }
        SportPatient sportPatient = new SportPatient();
        SportPatientId id = new SportPatientId(sport.getId(), patient.getId());
        sportPatient.setId(id);
        sportPatient.setSport(sport);
        sportPatient.setPatient(patient);
        Integer difAges = patient.getAge() - patientSportWs.getAgeAtStart();
        sportPatient.setAgeAtStartAsInteger(difAges);
        sportPatient.setHoursXWeek(patientSportWs.getHoursXWeek());
        return sportPatient;

    }

    /**
     *
     * @param PatientSurgeryWs
     * @param patient
     * @return
     */
    private SurgeryPatient convertToLocalPatientSurgery(PatientSurgeryWs patientSurgeryWs, Patient patient) throws ExceptionDAO {
        if (patientSurgeryWs == null) {
            return null;
        }
        Surgery surgery = FacadeDB.getInstance().getSurgerySyncBroker().getSurgeryByRemoteId(patientSurgeryWs.getSurgeryId());
        if (surgery == null) {
            return null;
        }
        SurgeryPatient surgeryPatient = new SurgeryPatient();
        SurgeryPatientId id = new SurgeryPatientId(patient.getId(), surgery.getId());
        surgeryPatient.setId(id);
        surgeryPatient.setSurgery(surgery);
        surgeryPatient.setPatient(patient);
        surgeryPatient.setAgeAtSurgery(patientSurgeryWs.getAgeAtSurgery());
        return surgeryPatient;
    }

    /**
     *
     * @param patientMedicineWs
     * @param patient
     * @return
     */
    private MedicinePatient convertToLocalPatientMedicine(PatientMedicineWs patientMedicineWs, Patient patient) throws ExceptionDAO {
        if (patientMedicineWs == null) {
            return null;
        }
        Medicine medicine = FacadeDB.getInstance().getMedicineSyncBroker().getMedicineByRemoteId(patientMedicineWs.getMedicineId());
        if (medicine == null) {
            return null;
        }
        MedicinePatient medicinePatient = new MedicinePatient();
        MedicinePatientId id = new MedicinePatientId(medicine.getId(), patient.getId());
        medicinePatient.setId(id);
        medicinePatient.setMedicine(medicine);
        medicinePatient.setPatient(patient);
        Integer difAges = patient.getAge() - patientMedicineWs.getAgeAtStart();
        medicinePatient.setAgeAtStartAsInteger(difAges);
        medicinePatient.setDosage(patientMedicineWs.getDosage());
        return medicinePatient;
    }

    /**
     *
     * @param patientPathologyWs
     * @param patient
     * @return
     */
    private PathologyPatient convertToLocalPatientPathology(PatientPathologyWs patientPathologyWs, Patient patient) throws ExceptionDAO {
        if (patientPathologyWs == null) {
            return null;
        }
        Pathology pathology = FacadeDB.getInstance().getPathologySyncBroker().getPathologyByRemoteId(patientPathologyWs.getPathologyId());
        if (pathology == null) {
            return null;
        }
        PathologyPatient pathologyPatient = new PathologyPatient();
        PathologyPatientId id = new PathologyPatientId(pathology.getId(), patient.getId());
        pathologyPatient.setId(id);
        Integer difAges = patient.getAge() - patientPathologyWs.getAgeAtStart();
        pathologyPatient.setAgeAtStartAsInteger(difAges);
        pathologyPatient.setCurrently(patientPathologyWs.isCurrently());
        pathologyPatient.setInherited(patientPathologyWs.isInherited());
        return pathologyPatient;
    }

    /**
     *
     * @param patientPathologyWs
     * @param patient
     * @return
     */
    private FamilyPatientBackground convertToLocalPatientFamilyBackground(PatientFamilyWs patientFamilyWs, Patient patient) throws ExceptionDAO {
        if (patientFamilyWs == null) {
            return null;
        }
        Family family = FacadeDB.getInstance().getFamilySyncBroker().getFamilyByRemoteId(patientFamilyWs.getFamilyId());
        if (family == null) {
            return null;
        }
        FamilyPatientBackground familyPatientBackground = new FamilyPatientBackground();
        FamilyPatientBackgroundId id = new FamilyPatientBackgroundId(family.getId(), patient.getId());
        familyPatientBackground.setId(id);
        familyPatientBackground.setFamily(family);
        familyPatientBackground.setPatient(patient);
        familyPatientBackground.setBackgroundCardiac(patientFamilyWs.isBackgroundCardiac());
        familyPatientBackground.setBackgroundCholesterol(patientFamilyWs.isBackgroundCholesterol());
        familyPatientBackground.setBackgroundDiabetic(patientFamilyWs.isBackgroundDiabetic());
        familyPatientBackground.setBackgroundHypertension(patientFamilyWs.isBackgroundHypertension());
        return familyPatientBackground;
    }

    /**
     *
     * @param habitsWs
     * @param patient
     * @return
     */
    private HabitPatient convertToLocalHabitPatient(PatientHabitsWs habitsWs, Patient patient) {
        if (habitsWs == null) {
            return null;
        }
        HabitPatient habitPatient = new HabitPatient(patient);
        habitPatient.setAngryLevel(habitsWs.getAngryLevel());
        habitPatient.setStressLevel(habitsWs.getStressLevel());
        habitPatient.setAutomedication(habitsWs.isAutomedication());
        habitPatient.setConsummingAlcohol(habitsWs.isConsummingAlcohol());
        habitPatient.setSedentary(habitsWs.isSedentary());
        habitPatient.setSmoked(habitsWs.isSmoked());
        habitPatient.setSmoking(habitsWs.isSmoking());
        habitPatient.setWorkPlace(habitsWs.getWorkPlace());
        habitPatient.setYearsOldAtFinish(habitsWs.getAgeAtEnd());
        habitPatient.setYearsOldAtStart(habitsWs.getAgeAtStart());
        habitPatient.setCigarettesPerDay(habitsWs.getCigarettesPerDay());
        habitPatient.setBlocksWalkedPerDay(habitsWs.getBlocksWalkedPerDay());
        return habitPatient;
    }

    /**
     *
     * @param date
     * @return
     */
    private Date xmlGregorianCalendarToDate(XMLGregorianCalendar calendar) {
        Date date = null;
        if (calendar != null) {
            GregorianCalendar cal = calendar.toGregorianCalendar();
            date = cal.getTime();
        }
        return date;
    }
}
